package com.wh.wisdomsite.xbox.server.controller.us;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.CommonFile;
import com.wh.wisdomsite.xbox.ba.service.ICommonFileService;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.us.EmployeeIn;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.us.entity.Employee;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.us.service.IEmployeeService;
import com.wh.wisdomsite.xbox.us.service.IUserService;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 员工Controller
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.controller.us
 * @author: 丁奕
 * @date: 2018-08-03 15:49
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/employee")
public class EmployeeController {

    private static final Log logger = LogFactory.getLog(EmployeeController.class);

    @Autowired
    private IEmployeeService iEmployeeService;

    @Autowired
    private ICommonFileService iCommonFileService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IProjectService iProjectService;


    /**
     * 页面跳转
     * @return
     */
    @RequiresPermissions("rules:us_employee_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index(){
        return "/us/employee/employeeList";
    }

    /**
     * 获取员工集合
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:us_employee_find")
    @RequestMapping(value = "/employeeList.do")
    public void employeeList(HttpServletResponse response, EmployeeIn in){
        try {
            logger.info("加载员工数据列表-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<Employee> page = new Page<Employee>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Employee> ewEmployee = new EntityWrapper<Employee>();
            ewEmployee.setEntity(new Employee());
            if(StringUtils.isNotEmpty(in.getName())){
                ewEmployee.like("e.name", in.getName());
            }
            if(StringUtils.isNotEmpty(in.getJobNumber())){
                ewEmployee.like("e.jobNumber", in.getJobNumber());
            }
            if(StringUtils.isNotEmpty(in.getCompanyId())){
                ewEmployee.eq("e.companyId", in.getCompanyId());
            }
            if(StringUtils.isNotEmpty(in.getOfficeId())){
                ewEmployee.eq("e.officeId", in.getOfficeId());
            }
            if(StringUtils.isNotEmpty(in.getPrId())){
                ewEmployee.eq("e.prId", in.getPrId());
            }
            if(StringUtils.isNotEmpty(in.getEmployeeJob())){
                ewEmployee.eq("e.employeeJob", in.getEmployeeJob());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewEmployee = UserUtils.setEntityWrapper(ewEmployee, "co", "off", "pr");
            }
            ewEmployee.orderBy("e.createDate", true);
            Page<Map<String, Object>> employeePage = iEmployeeService.getMapsPage(page, ewEmployee);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if(employeePage.getRecords().size() > 0){
                for(Map<String, Object> employee : employeePage.getRecords()){
                    JSONObject object = new JSONObject(employee);
                    object.put("id",employee.get("emId"));
                    if(employee.get("thrClsCertType") != null){
                        object.put("thrClsCertType",new JSONObject(employee.get("thrClsCertType")));
                    }
                    if(employee.get("employeeJob") != null){
                        object.put("employeeJob",new JSONObject(employee.get("employeeJob")));
                    }
                    if(employee.get("company") != null){
                        object.put("company",new JSONObject(employee.get("company")));
                    }
                    if(employee.get("office") != null){
                        object.put("office",new JSONObject(employee.get("office")));
                    }
                    if(employee.get("project") != null){
                        object.put("project",new JSONObject(employee.get("project")));
                    }
                    array.put(object);
                }
            }
            json.put("total",employeePage.getTotal());
            json.put("rows",array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载员工数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载员工数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取员工List
     * @param response
     * @param in
     */
    @RequestMapping("getEmployeeList.do")
    public void getTreeCompany(HttpServletResponse response,EmployeeIn in) {
        try{
            logger.info("获取员工List-->>开始");
            JSONArray array = iEmployeeService.getEmployeeList(in);
            ResManager.getTextOut(response).print(array);
            logger.info("获取员工List-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("获取员工List-->>Exception" + e.getMessage());
        }
    }

    /**
     * 员工详情
     * @param employeeIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:us_employee_view")
    @RequestMapping("employeeDesc.do")
    public String employeeDesc(EmployeeIn employeeIn, HttpServletRequest request) {
        logger.info("员工详情-->>开始");
        Map<String , Object> employee = iEmployeeService.getMapById(employeeIn.getId());
        String prNames = "";
        if(null != employee.get("prFinished")){
            String prFinished = (String)employee.get("prFinished");
            prNames = getPrNamesByPrIds(prFinished);
        }
        if(null != employee.get("createBy")){
            employee.put("createBy", UserMapManager.getUserLoginNameInMap(employee.get("createBy").toString()));
        }
        if(null != employee.get("updateBy")){
            employee.put("updateBy", UserMapManager.getUserLoginNameInMap(employee.get("updateBy").toString()));
        }
        request.setAttribute("employee", employee);
        request.setAttribute("prNames", prNames);
        logger.info("员工详情-->>结束");
        return "/us/employee/employeeDesc";
    }

    /**
     * 跳转至添加或修改页面
     * @return
     */
    @RequestMapping("/toEmployeeOption")
    public String toEmployeeOption(String id, HttpServletRequest request){
        logger.info("添加修改员工跳转-->>开始");
        if(StringUtils.isNotEmpty(id)){
            //注入employee参数
            Employee employee = iEmployeeService.selectById(id);
            String prNames = getPrNamesByPrIds(employee.getPrFinished());
            Map<String, Object> employeePhoto = iEmployeeService.getMapById(id);
            request.setAttribute("employee", employee);
            request.setAttribute("employeePhoto",employeePhoto);
            request.setAttribute("prNames",prNames);
        }
        logger.info("添加修改员工跳转-->>开始");
        return "us/employee/employeeOption";
    }

    /**
     * 更新或者修改
     * @param employee
     * @param response
     */
    @RequiresPermissions("rules:us_employee_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Employee employee,User user, CommonFile commonFile, String fileName, HttpServletResponse response){
        try {
            User curUser = UserUtils.getCurrentUser();
            //判断员工是否已经存在,存在即更新.否则为添加
            if(employee.getCompanyId() == null){
                employee.setCompanyId(UserUtils.getServerSessionUser().getDirectCompany().getCompanyId());
                user.setCompanyId(UserUtils.getCurrentUser().getCompanyId());
            }
            //修改项目中项目负责人名字
            if(StringUtils.isNotEmpty(employee.getPrId())){
                Project project = new Project();
                project.setPrId(employee.getPrId());
                project.setPrLeader(employee.getName());
                iProjectService.updateById(project);
            }
            //对完结的项目进行归档
            String prFinished = employee.getPrFinished();
            //选择已完结，在归档项目中不包含此项目情况才做添加
            if("2".equals(employee.getPrEndState())){
                if(StringUtils.isNotEmpty(employee.getPrId()) && !prFinished.contains(employee.getPrId())){
                    if(prFinished.length() > 0){
                        prFinished = prFinished + "," + employee.getPrId();
                    }else{
                        prFinished = prFinished + employee.getPrId();
                    }
                    employee.setPrFinished(prFinished);
                }
            }else{
                //选择未完结，在归档项目中若存在当前项目则移除
                if(StringUtils.isNotEmpty(employee.getPrId()) && prFinished.contains(employee.getPrId())){
                    if(prFinished.contains(",")){
                        prFinished = prFinished.replace("," + employee.getPrId(),"");
                    }else{
                        prFinished = prFinished.replace(employee.getPrId(),"");
                    }
                    employee.setPrFinished(prFinished);
                }
            }
            if(StringUtils.isNotEmpty(employee.getEmId())){
                logger.info("修改员工-->>开始");
                employee.setUpdateBy(curUser.getUsId());
                employee.setUpdateDate(new Date());
                user.setCompanyId(UserUtils.getCurrentUser().getCompanyId());
                //设置附件信息
                if(StringUtils.isNotEmpty(commonFile.getFileId())) {
                    if(!employee.getEmployeePhoto().equals(commonFile.getFileId())){
                        commonFile.setName(fileName);
                        addCommonFile(employee, commonFile, curUser);
                    }
                }
                iEmployeeService.updateById(employee);
                iUserService.updateById(user);
                logger.info("修改员工-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("员工更新成功"));

            }else {
                logger.info("添加员工-->>开始");
                employee.setCreateBy(curUser.getUsId());
                employee.setCreateDate(new Date());
                employee.setEmId(UUID.randomUUID().toString().replace("-",""));
                if(StringUtils.isNotEmpty(commonFile.getFileId())){
                    //添加附件信息
                    addCommonFile(employee, commonFile, curUser);
                }
                iEmployeeService.insert(employee);
                logger.info("添加员工-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("员工添加成功"));
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作员工-->>Exception" + e.getMessage());
        }
    }

    /**
     * 添加附件信息
     * @param employee
     * @param commonFile
     * @param curUser
     */
    private void addCommonFile(Employee employee, CommonFile commonFile, User curUser) {
        commonFile.setFkId(employee.getEmId());
        commonFile.setCreateby(curUser.getUsId());
        commonFile.setCreatedate(new Date());
        commonFile.setCompCode(UserUtils.getServerSessionUser().getFinalCompCode());
        iCommonFileService.insert(commonFile);
        employee.setEmployeePhoto(commonFile.getFileId());
    }

    /**
     * 删除员工
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:us_employee_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除员工-->>开始");
            iEmployeeService.deleteById(id);
            logger.info("删除员工-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("员工删除成功"));
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除员工-->>Exception" + e.getMessage());
        }
    }

    /**
     * 根据项目ids获取项目名称
     * @param prIds
     */
    public String getPrNamesByPrIds(String prIds){
        String prNames = "";
        try{
            if(StringUtils.isNotEmpty(prIds)){
                EntityWrapper<Project> ewProject = new EntityWrapper<Project>();
                ewProject.setEntity(new Project());
                ewProject.in("p.prId",prIds);
                List<Project> projectList = iProjectService.selectList(ewProject);
                for(Project project : projectList){
                    prNames = prNames + project.getPrName() + ",";
                }
                if(prNames.length() > 0){
                    prNames =  prNames.substring(0,prNames.length() - 1);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return prNames;
    }
}
